package com.vf.cloud.paas.app.master.api.sys.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.vf.cloud.paas.app.master.api.sys.service.IUser;
import com.vf.cloud.paas.app.master.common.domain.User;

@Service
public class UserImpl implements IUser {

	public User getById(String id) {
		return User.dao.findById(id);

	}

	public List<User> list(User param) {
		String _sql="select id,name,username,phone,pid,is_limit,status,role_mark from " + User.TABLE_NAME + " where pid=? ";
		if(StrKit.equals("-1", param.getId())) {
			if(!StrKit.isBlank(param.getName())) {
				_sql="select * from " + User.TABLE_NAME + " where pid=? and  name like '%"+param.getName()+"%' ";
			}
		}else {
			_sql="select id,name,username,phone,pid,is_limit,status,role_mark from " + User.TABLE_NAME + " where id=? ";
		}
		
		List<User> users = User.dao.find(_sql, param.getId());
		for (User u : users) {
			param.setId(u.getId());
			u.setChildren(getChildrens(param));
		} 
		return users;
	}
	
	
	public List<User> getChildrens(User param) {
		String _sql="select id,name,username,phone,pid,is_limit,status,role_mark from " + User.TABLE_NAME + " where pid=? ";
		if(!StrKit.isBlank(param.getName())) {
			_sql="select * from " + User.TABLE_NAME + " where pid=? and  name like '%"+param.getName()+"%' ";
		}
		List<User> users = User.dao.find(_sql, param.getId());
		for (User u : users) {
			param.setId(u.getId());
			u.setChildren(getChildrens(param));
		}
		return users;
	}
	
	
	
	public List<User> getChildren(User param) {
		
		String _sql="select * from " + User.TABLE_NAME + " where pid=? ";
		if(!StrKit.isBlank(param.getName())) {
			_sql="select * from " + User.TABLE_NAME + " where pid=? and name like '%"+param.getName()+"%' ";
		}
		
		List<User> users = User.dao.find(_sql, param.getPid());
		
		for (User u : users) {
			u.setChildren(getChildren(u));
		}
		return users;
	}

	

//	@Override
//	public List<User> getChildrens(User param) {
//		if (!StrKit.isBlank(param.getName())) {
//			String sql = "SELECT T.*, (CASE  WHEN (SELECT COUNT(ID) AS COUNT FROM " + User.TABLE_NAME
//					+ " WHERE PID=T.ID)>0 THEN TRUE ELSE  FALSE END ) AS leaf  FROM " + User.TABLE_NAME
//					+ "  T WHERE T.PID=?  and t.name like '%" + param.getName() + "%'   ORDER BY T.create_time desc";
//			return User.dao.find(sql, param.getPid());
//		} else {
//			String sql = "SELECT T.*, (CASE  WHEN (SELECT COUNT(ID) AS COUNT FROM " + User.TABLE_NAME
//					+ " WHERE PID=T.ID)>0 THEN TRUE ELSE  FALSE END ) AS leaf  FROM " + User.TABLE_NAME
//					+ "  T WHERE T.PID=?    ORDER BY T.create_time desc";
//			return User.dao.find(sql, param.getPid());
//		}
//	}

	@Override
	public boolean delete(User user) {
		Db.delete("delete from "+User.TABLE_NAME+" where pid=?",user.getId());
		return user.delete();
	}
}
